 /*
  * Copyright (c) 2006, 2023, wuyahan 编写
  *
  */
 package com.repair.filter;

 import org.springframework.http.HttpMethod;
 import org.springframework.http.HttpStatus;
 import org.springframework.util.StringUtils;

 import javax.servlet.*;
 import javax.servlet.annotation.WebFilter;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;

 /**
  * <p>Project: server_zhang - LoginFilter
  * <p>Powered by wuyahan On 2023-04-11 08:46:51
  *
  * @author wuyahan [tianwenle2000@163.com]
  * @version 1.0
  * @since 17
  */
 @WebFilter(value = "/**", filterName = "corsFilter")
 public class CorsFilter implements Filter {


     @Override
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
         System.out.println("request.getRemoteAddr() = " + request.getRemoteAddr());
         HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         String origin = httpServletRequest.getHeader("Origin");
         HttpServletResponse httpServletResponse = (HttpServletResponse) response;
         // 设置允许所有请求跨域
         String corsAllowHeaders = httpServletRequest.getHeader("Access-Control-Request-Headers");
         httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
         httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
         httpServletResponse.setHeader("Access-Control-Allow-Headers", corsAllowHeaders);
         httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
         httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
         if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(httpServletRequest.getMethod())) {
             httpServletResponse.setStatus(HttpStatus.OK.value());
             return;
         }

         filterChain.doFilter(request, response);

     }


 }
